<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useDataPublicStore} from "@/stores/dataPublicStore.ts";
import FileUpload from "@/views/PublicCom/ImageFilesUpload.vue";
import CameraCapture from "@/views/PublicCom/cameraCapture.vue";
import ContextMenu from "@imengyu/vue3-context-menu";
import {modifyOneEquipmentTransferAPI} from '@/apis/equipmentTransfer.ts';
import {useLocationStore} from '@/stores/locationStore.ts'
import router from "@/router/index.ts";
import {useRoute} from "vue-router";
import {useEquipmentTransferStore} from "@/stores/equipmentTransferStore.ts";

// 获取设备类型
const locationStore=useLocationStore();
locationStore.getLocationInfo(1,100);

// 获取pinia数据，用于拍照和图片上传组件使用
const dataPublicStore=useDataPublicStore();

const route=useRoute();

const equipmentTransferStore=useEquipmentTransferStore();
const equipmentTransfer=ref({});

// 显示在页面上的图像地址数组
const photoList=ref([]);
// y用于比较被删除图像的数组
const tempPhotoList=ref([]);
// // 用于往后端传送需要删除的图像的地址数组
const checkList=ref([]);


const srcList=ref<string>([]);
onMounted(async ()=>{

  // todo 好好看看，这里的逻辑也可能有问题你，应该是用这个id获取到equipment的数据，而不是equipmentTransfer的数据
  if (route.params.id===null||route.params.id===undefined){
    await  router.push({path:'/home/equipment/equipmentTransfer'})
  }
  else{
    await equipmentTransferStore.getOneByIdStore(route.params.id);
    equipmentTransfer.value=equipmentTransferStore.equipTransferData;

    if (equipmentTransfer.value.equipTransferPhotoList.length>0){

      equipmentTransfer.value.equipTransferPhotoList.forEach((item:string)=>{
        photoList.value.push(item.photoUrl);
        tempPhotoList.value.push(item.photoUrl);
      })


      for (let i = 0; i < equipmentTransfer.value.equipTransferPhotoList.length; i++) {
        srcList.value.push(equipmentTransfer.value.equipTransferPhotoList[i].photoUrl)
      }
    }
  }
})



// 专门修正element-ui中图片预览必须要从第一张开始的bug
function  getPreviewImgList (index:number) {
  let arr = [];
  for (let i = 0; i < photoList.value.length; i++) {
    arr.push(photoList.value[i + index]);
    if (i + index >= photoList.value.length - 1) { // 为了取后边小值（采用绝对值）
      index = 0 - (i + 1);
    }
  }
  return arr;
}

const onContextMenu=(e:MouseEvent,index:number)=>{
  ContextMenu.showContextMenu({
    x:e.x,
    y:e.y,
    items:[
      {
        label:'删除',
        // 这里有三个数组，页面一打开时，photoList和tempPhotoList中都包含了已经存在的图片地址
        // checkList数组是空白数组
        onClick() {
          // 右键删除时，photoList会把点选的元素删除
          photoList.value.splice(index,1);
          // 遍历tempPhotoList数组，如果发现当中一个元素不包含在photoList数组中，就把这个元素存放在checkList数组中
          // 这个就可以告诉后端，需要删除的是那个图片
          tempPhotoList.value.forEach((item)=>{
            if (!photoList.value.includes(item)){
              checkList.value.push(item);
            }
          })
        },
      }
    ]
  })
}

// 控制提交按钮的可操作性
const disableSwitch=ref(false);
const formData=new FormData();

const receivingProject=ref('');



// 显示进度条配合函数
const format=(percentage:number)=>{
  return percentage===100?'100%':`${percentage}`
}


// 时间戳变成真实时间
// function getDate(time: number) {
//   let date = new Date(time);
//   let Y=date.getFullYear()+'年';
//   let M=(date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '月';
//   let D=date.getDate()+'日';
//   let h=date.getHours()+'时';
//   let m=date.getMinutes()+'分';
//   return Y+M+D+h+m;
// }

const description=ref('');



const modifyOneSummit=async ()=>{
  disableSwitch.value=true;
  formData.append('id',equipmentTransfer.value.id);
  formData.append('encode',equipmentTransfer.value.encode);
  formData.append('receivingProject',receivingProject.value);
  formData.append('description',description.value)
  formData.append('photoList',checkList.value);
  if (dataPublicStore.uploadFileList.length>0){
    dataPublicStore.uploadFileList.forEach((item:File)=>{
      formData.append('photoFiles',item)
    });
  }
  if (dataPublicStore.photoFileList.length>0){
    dataPublicStore.photoFileList.forEach((item:File)=>{
      formData.append('photoFiles',item)
    })
  }
  disableSwitch.value=true;
  await modifyOneEquipmentTransferAPI(formData);
  dataPublicStore.setUploadFileList([]);
  dataPublicStore.setPhotoFiles([]);
  dataPublicStore.saveDataObject({});
  dataPublicStore.setOnUploadProgress(0);
  await router.push({path:'/home/equipment/equipmentTransfer'});
}



</script>

<template>
  <!--  进度条显示-->
  <!--  进度条-->
  <el-progress :percentage="dataPublicStore.onUploadProgress" :format="format"    :stroke-width="5" v-show="dataPublicStore.onUploadProgress" style="margin: 0;padding: 0" ></el-progress>
  <!--  面包屑-->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/equipment/equipmentTransfer`}" >设备出场列表</el-breadcrumb-item>
      <el-breadcrumb-item  >设备出场详情修改</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="divTable">
    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >设    备    出    场    详    细    信    息</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">设备名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  ">{{equipmentTransfer.eqName}}</td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >设备品牌</td>
        <td style="width: 350px;height: 15px ; text-align: center   ">{{equipmentTransfer.brand}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备型号</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{equipmentTransfer.model}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >设备转场编码</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{equipmentTransfer.encode}}</td>
      </tr>

      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备数量单位</td>
        <td style="width: 350px;height: 15px;text-align: center  ">{{equipmentTransfer.pieces}}</td>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >设备数量</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{equipmentTransfer.number}}</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >原设备所在地</td>
        <td style="width: 350px;height: 15px;text-align: center   ">{{equipmentTransfer.sendingProject}}</td>

        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">现设备所在地</td>

        <td style="width: 230px;height: 15px;text-align: center;padding: 0">
          <el-select
              v-model="receivingProject"
              clearable
              placeholder="Select"

          >
            <el-option
                v-for="(item,index) in locationStore.locationInfo"
                :key="index"
                :label="item.locationAddress"
                :value="item.locationAddress"
            />
          </el-select></td>
      </tr>

      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">设备类型</td>
        <td colspan="3" style="width: 850px;height: 15px;text-align: center">{{equipmentTransfer.typeName}}</td>
      </tr>
      <tr>
        <td  style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">备注</td>

        <td colspan="3" style="width: 850px;height: 15px;text-align: center"> <el-input  v-model="description" /></td>
      </tr>
<!--      <tr>-->
<!--        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">创建人</td>-->
<!--        <td style="width: 350px;height: 15px;text-align: center  ">{{equipmentTransfer.createBy}}</td>-->
<!--        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >最后修改人</td>-->
<!--        <td style="width: 350px;height: 15px;text-align: center   ">{{equipmentTransfer.lastUpdateBy}}</td>-->
<!--      </tr>-->
<!--      <tr>-->
<!--        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">创建时间</td>-->
<!--        <td style="width: 350px;height: 15px;text-align: center  ">{{getDate(equipmentTransfer.createTime)}}</td>-->
<!--        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >最后修改时间</td>-->
<!--        <td style="width: 350px;height: 15px;text-align: center   ">{{ getDate(equipmentTransfer.updateTime)}}</td>-->
<!--      </tr>-->
      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"></td>
      </tr>
      <tr >
        <td colspan="4" >
          <div style="font-family: 'Microsoft Himalaya',serif;font-weight: bold;margin: 10px;padding: 2px">已有图片</div>
          <div class="block" style="margin: 20px">
            <el-image v-for="(ele,index) in photoList" :key="index"
                      style="width: 150px; height: 100px"
                      :src="ele"
                      :zoom-rate="1.2"
                      :max-scale="5"
                      :min-scale="0.5"
                      :preview-src-list="getPreviewImgList(index)"
                      fit="cover"
                      @contextmenu.prevent
                      @contextmenu.stop="onContextMenu($event,index)"
            >
            </el-image>
          </div>
        </td>
      </tr>
      <tr>
        <td colspan="4">
          <CameraCapture/>
        </td>
      </tr>


      <tr>
        <td colspan="4">
          <FileUpload/>
        </td>
      </tr>
      <tr>
        <td colspan="4" style="background:#EFF6FF ">
          <el-button @click="modifyOneSummit" type="primary" :disabled="disableSwitch" style="margin-top: 1%;margin-bottom: 1%" >确认修改</el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>



</template>


<style scoped lang="scss">
.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: absolute;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>